let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selIndex: 0,
    categoryList:[],
    productList: [],
    categoryImg: '',
    prodid:'',
    number:0,
    total:0.00

  },
  //接口返回数据
  Cates: [],

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    /**
     * 1,先判断本地储存中有没有旧的缓存数据
     * 本地存储数据格式：
     * {time.Data.now(),data:[.....]}
     * 2，没有数据就发送请求，
     * 3，有旧数据且旧数据没有过期，直接使用本地储存中的旧数据
     */
    let that = this;
    that.setData({
      platform:app.globalData.platform,
       width:app.globalData.windowWidth,
      height:app.globalData.windowHeight,
      statusBarHeight:app.globalData.statusBarHeight,
      navHeight:app.globalData.navHeight,
      marginTop:app.globalData.navTitleTop,
      domain:app.globalData.domain,
      safeHeight :app.globalData.safeHeight
    
    })
   

  },
  onMenuTab: function (e) {
    console.log(e);
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    let rightContent = this.Cates[index].good;
    const shopcart = wx.getStorageSync('shopcart');
    if(shopcart != undefined && shopcart != ''){
      rightContent.forEach(ele=>{
        shopcart.forEach(element=>{
          if(ele.id == element.id){
              ele.shopcart = element;
          }
        })
      })
    }
    console.log(rightContent)
    this.setData({
      selIndex: index,
      rightContent:rightContent
    });
  },

  //获取分类数据
  getCates() {
    let that = this;
    const shopcart = wx.getStorageSync('shopcart');
    console.log('----getCates------')
    console.log(shopcart);
    console.log('----getCates-- end---')
   wx.request({
     url: app.globalData.domain+'wechat/shop/getCate',
     data:{'from':"3"},
    success:res => {
      console.log(res)
      var cates =res.data.cate;
      if(shopcart!=undefined && shopcart != ''){
        cates.forEach(ele=>{
            ele.good.forEach(e=>{
            shopcart.forEach(element=>{
              if(e.id == element.id){
                  e.shopcart = element;
              }
            })
          })
        })
      }
      this.Cates = cates;

      //把结构数据存入本地缓存
      wx.setStorageSync('cates', {
        time: Date.now(),
        data: this.Cates
      });

      //构造左侧菜单数据
      let leftMenuList = this.Cates;
      //构造右侧商品数据
      let rightContent = this.Cates[0].good;
      this.setData({
        leftMenuList,
        rightContent,
      })
    }
  })
  },
 addShopcart(e){
   console.log(e);
   var data = e.currentTarget.dataset;
   var id = data.id;
   var price = data.price;
   var name = data.name;
   var img = data.img;
   var shopcarts =[]
   var shopcart = this.data.shopcart;
   console.log(shopcart);
   var good ={id:id,price:price,num:1,name:name,img:img};
   var number=0;
  var total=0.00;
 // var cates = this.Cates;
  var rightContent = this.data.rightContent;
  rightContent.forEach(ele=>{
    if(id == ele.id){
      if(ele.shopcart){
          ele.shopcart.num = ele.shopcart.num+1;
      }else{
          ele.shopcart = good;
      }
    }
  });
  this.setData({
    rightContent:rightContent
  })

   if(shopcart == '' || shopcart == undefined){
   console.log('shopcart is null')
   var shopcarts = [];
   shopcarts.push(good);
   console.log(shopcarts);
   wx.setStorageSync('shopcart', shopcarts)
   this.setData({
     shopcart:shopcarts,
     number:1,
     total:price,
     
   })
  
   }else{
     //console.log('shopcart not null');
     //console.log(shopcart)
     var i=0;
     shopcart.forEach(ele => {
      
        if(ele.id == id){
          
          ele.num=ele.num+1;
          i=1;
          
         // break;
        }
     });
     if(i==0){
        shopcart.push(good);
     }
     shopcart.forEach(ele=>{
        number = number + ele.num;
        total = total + ele.num*ele.price;
     })
     wx.setStorageSync('shopcart', shopcart)
     let totals = parseFloat(total).toFixed(2);
     this.setData({
      shopcart:shopcart,
      number:number,
      total:totals,
      
    })
   
   }
 },
 reduceShopcart(e){
    console.log(e);
    var data = e.currentTarget.dataset;
    var id = data.id;
    var price = data.price;
   // var shopcarts =[]
    var shopcart = this.data.shopcart;
    var index;
    var i=0;
    var number=0;
    var total=0.00;
    shopcart.forEach(ele=>{
      if( ele.id == id){
        if(ele.num>1){
          ele.num = ele.num - 1;
        }else{
          index = i;
        }
      }
      i++;
    })
    shopcart.splice(index, 1); 
    console.log(shopcart);

    var rightContent = this.data.rightContent;
    rightContent.forEach(ele=>{
      if(ele.id == id){
        if(ele.shopcart){
          if(ele.shopcart.num>1){
            ele.shopcart.num = ele.shopcart.num - 1;
          }else{
            delete ele.shopcart;
          }
        }
      }
    })
    shopcart.forEach(ele=>{
      number = number + ele.num;
      total = total + ele.num*ele.price;
   })
   wx.setStorageSync('shopcart', shopcart)
   let totals = parseFloat(total).toFixed(2);
    this.setData({
      rightContent:rightContent,
      shopcart:shopcart,
      number:number,
      total:totals,
      
    })
 },
  //左侧菜单的点击事件
  handleItemTap(e) {
    /*
    1,获取被点击菜单的索引
    2，给data中的currentIndex赋值
    3,根据不同索引渲染右侧内容
    */
    const {
      index
    } = e.currentTarget.dataset;
    let rightContent = this.Cates[index].children;
    this.setData({
      currentIndex: index,
      rightContent,
      //设置右侧距离顶部距离
      scrollTop:0,
    });

  },
goShopcart(e){
  var open = wx.getStorageSync('open');
  if(open.mobile == 'NULL'){
      this.showModals('请先登录','../mine/getPhone','#')
  }
  wx.navigateTo({
    url: '../shopcart/index',
  })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const Cates = wx.getStorageSync("cates");
    var shopcart = wx.getStorageSync('shopcart');
    if (!Cates) {
      //不存在，获取数据
      this.getCates();
    } else {
      //本地有缓存
      if (Date.now() - Cates.time > 1000 * 30) {
        //超过10s就重新发送请求
        this.getCates();
      } else {
        //可以使用本地缓存数据
        this.Cates = Cates.data;
        //构造左侧菜单数据
        let leftMenuList = this.Cates.map(v => v.cat_name);
        //构造右侧商品数据
        let rightContent = this.Cates[0].good;
        if(shopcart!=undefined && shopcart != ''){
          rightContent.forEach(ele=>{
            shopcart.forEach(element=>{
              if(ele.id == element.id){
                  ele.shopcart = element;
              }
            })
          })
        }
       
        this.setData({
          leftMenuList,
          rightContent,
        })
      }
    }

    
    
    if(shopcart != undefined && shopcart!=''){
      var number=0;
      var total=0.00;
      shopcart.forEach(ele=>{
          number = number + ele.num;
          total = total + ele.num*ele.price
      })
      let totals = parseFloat(total).toFixed(2);
      this.setData({
        shopcart:shopcart,
        number:number,
        total:totals
      })
    }
   
  },
  toSearch(e){
    console.log(e);
    var keyword = e.detail.value;
    let that = this;
    if(keyword){
      wx.request({
         url: app.globalData.domain+'wechat/shop/search',
      data:{'from':'shop',keyword:keyword},
      success:res => {
        console.log(res);
        if(res.statusCode==200){
          that.setData({
            rightContent:res.data.list
          })
         
        }
      }
    })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
